/**
 * @license
 * Copyright 2021 Du Tian Wei
 * SPDX-License-Identifier: Apache-2.0
 */
(function () {
    const ROOT_URL = "../jsruntime/test/";
    const PAGE_URL = "index.html";
    let windows = [];
    let window_sn = 0;
    let jspreviewer;
    function newWindow(result) {
        let assets = {};
        let arr_assets = [];
        let datas = VFS.partition.assets._storage.datas
        for (let key in datas) {
            let d = datas[key].slice(0);
            assets[key] = d;
            arr_assets.push(d);
        }
        let runProjectCmd = { "cmd": "runProject", "bytes": result, fsm: "Start.Main", assets };
        let sn = ++window_sn;
        let w = {
            id: sn, enable: true, style: { width: '375px', height: '640px' }
        };
        let index = windows.length;
        w.onVisibleChange = function (v) {
            setTimeout(() => {
                windows.splice(index, 1);
                w.iframe.remove();
                // windows[index] = null;
            }, 5);
        };
        windows.push(w);
        setTimeout(() => {
            let iframes = jspreviewer.$refs.jsprevieweriframe;
            let iframe = iframes[iframes.length - 1];
            w.iframe = iframe;
            iframe.contentWindow.window.onload = () => {
                iframe.contentWindow.postMessage(runProjectCmd, arr_assets);
            };
            iframe.contentWindow.postMessage(runProjectCmd, arr_assets);
            jspreviewer.dragData.push(jspreviewer.$refs.jspreviewerinst[iframes.length - 1].$vnode.componentInstance._data.dragData);
        }, 0);
    }
    Vue.component('jspreviewer_add', {
        props: [],
        data: {},
        template: '\
        <tooltip\
            content="新预览窗口" :delay="1000">\
            <a class="headerBtn">\
                <icon type="ios-apps" @click="newWindow" size="20"\
                    style="cursor:pointer;vertical-align: -2px;"></icon>\
            </a>\
        </tooltip>',
        methods: {
            newWindow() {
                OpenBlock.exportExePackage((err, result) => {
                    if (!err) {
                        newWindow(result);
                    }
                });
            }
        }
    });
    Vue.component('jspreviewer', {
        props: [],
        data() {
            return {
                enable: true,
                dragData: [],
                windows,
            };
        },
        template: '\
        <template>\
        <div>\
        <modal v-for="(win,index) in windows"\
         :key="win.id" @on-visible-change="windows[index].onVisibleChange" \
         class="jspreviewer" ref="jspreviewerinst" :mask-closable="false" :mask="false"\
         footer-hide draggable v-model="win"  :title="OpenBlock.i(\'Simulator\')+\'-\'+win.id" \
         :width="win.style.width"\
         closable="false" transfer="false">\
            <select name="screen" class="screen-select" ref="jsprevieweriframe_screen"\
             @change="changeScreen(win,$event)">\
                <option value="666px">1333 16:9</option>\
                <option selected value="640px">1280</option>\
                <option value="600px">1200 16:10</option>\
                <option value="500px">1000 3:4</option>\
                <option value="375px">750 1:1</option>\
                <option value="281px">562 4:3</option>\
                <option value="234px">468 10:16</option>\
                <option value="210px">421 9:16</option>\
            </select>\
        <button @click="refresh(win)">R</button>\
        <iframe ref="jsprevieweriframe" class="jsprevieweriframe" scrolling="no"\
         src="' + ROOT_URL + PAGE_URL + '"\
         :style="win.style">\
        </frame>\
        </modal>\
    </div>\
    </template>',
        mounted() {
            jspreviewer = this;
            this.$watch('dragData', function (newValArr, oldVal) {
                newValArr.forEach(newVal => {
                    if (!newVal.dragging) {
                        if (newVal.y < 0) {
                            newVal.y = 0;
                        }
                        if (newVal.x < -300) {
                            newVal.x = -300;
                        }

                        if (newVal.y > window.innerHeight - 100) {
                            newVal.y = window.innerHeight - 100;
                        }
                        if (newVal.x > window.innerWidth - 100) {
                            newVal.x = window.innerWidth - 100;
                        }

                    }
                });
            }, { deep: true, immediate: true });
        },
        methods: {
            closeSimular(win, index) {
                console.log(win, index);
            },
            changeScreen(win, evt) {
                win.style.height = evt.target.value;
            },
            refresh(win) {
                let runProjectCmd = {
                    "cmd": "restart",
                    fsm: "Start.Main"
                };
                win.iframe.contentWindow.postMessage(runProjectCmd);
            }
        }
    });
    OpenBlock.onInited(() => {
        class Simulator extends OBConnector {
            pageUrl;
            loading = false;
            /**
             * @type {Window}
             */
            constructor() {
                super();
                this.pageUrl = "../jsruntime/test/index.html";
            }
            setLoading() {
                this.loading = true;
            }
            unsetLoading() {
                this.loading = false;
            }
            loadConfig() {
                let env = ROOT_URL + 'env/'
                let jsarr = [
                    env + 'i18n_zh.js',
                    env + 'nativeEvent.js',
                    env + 'native.js',
                ];
                var xmlpath = env + "nativeBlocks.xml";
                OpenBlock.loadNativeInfo(jsarr, xmlpath);
            }
            runProject() {
                if (this.loading) {
                    UB_IDE.$Notice.open({
                        title: '正在打开工程，请稍后。'
                    });
                    return;
                }
                let assets = {};
                let arr_assets = [];
                let datas = VFS.partition.assets._storage.datas
                for (let key in datas) {
                    let d = datas[key].slice(0);
                    assets[key] = d;
                    arr_assets.push(d);
                }
                OpenBlock.exportExePackage((err, result) => {
                    if (!err) {
                        let runProjectCmd = {
                            "cmd": "runProject",
                            "bytes": result,
                            fsm: "Start.Main",
                            assets
                        };
                        if (windows.length == 0) {
                            newWindow(result);
                        }
                        setTimeout(() => {
                            jspreviewer.$refs.jsprevieweriframe.forEach(iframe => {
                                iframe.contentWindow.window.onload = () => {
                                    iframe.contentWindow.postMessage(runProjectCmd, arr_assets);
                                };
                                iframe.contentWindow.postMessage(runProjectCmd, arr_assets);
                            });
                        }, 5);
                    }
                });
            }
        }
        window.Simulator = Simulator;
        UB_IDE.ensureExtComponent('subwindows', 'jspreviewer');
        UB_IDE.ensureExtComponent('lefttoolbox', 'jspreviewer_add');
    });
})();